#include "IOStream.h"

using namespace neiderra::core;

win32OutputStream::win32OutputStream(Core *core)
: iOutputStream (core) 
{
}

win32OutputStream::~win32OutputStream()
{
}

bool win32OutputStream::open(const char* filename)
{
	filename_ = filename;
	// fixme: LPCWSTR bugs str content
	file_ = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
	return (file_ != INVALID_HANDLE_VALUE)?true:false;
}

void win32OutputStream::close()
{
	CloseHandle(file_);
}

int win32OutputStream::write(const char* buf, int n)
{
	DWORD rb;
	WriteFile(file_, buf, DWORD(n), &rb, NULL);
	return rb;
}

int win32OutputStream::write(const char* buf)
{
	int i;
	for(i=0; buf[i]!='\0'; i++);
	write(buf, i);
	return i;
}

int win32OutputStream::writeln(const char* buf)
{
	int i=write(buf);
	char endl[2] = {0x0D, 0x0A};
	write(endl, 2);
	return i+2;
}


//
// input stream implementation
//

win32InputStream::win32InputStream(Core* core)
: iInputStream(core)
{
	_opened = false;
}

win32InputStream::~win32InputStream()
{
}

bool win32InputStream::open(const char* filename)
{
	if(_opened)
		if(filename_ != "") CloseHandle(file_);
	file_ = CreateFile( filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
	filename_ = filename;
	_opened = (file_ != INVALID_HANDLE_VALUE)?true:false;
	return _opened;
}

void win32InputStream::close()
{
	if(_opened){
		_opened = false;
		CloseHandle(file_);
	}
}

int win32InputStream::read(char* buf, int n)
{
	DWORD rb;
	ReadFile(file_, buf, DWORD(n), &rb, NULL);
	return rb;
}

int win32InputStream::size()
{
	return GetFileSize(file_, NULL);
}

int win32InputStream::seek(long n, SeekType type)
{
	switch(type)
	{
	case stBegin: return SetFilePointer(file_,n,NULL,FILE_BEGIN);
	case stCurrent: return SetFilePointer(file_,n,NULL,FILE_CURRENT);
	case stEnd: return SetFilePointer(file_,n,NULL,FILE_END);
	default: return -1;
	}
}

long win32InputStream::pos()
{
	return SetFilePointer(file_, 0, NULL, FILE_CURRENT);
}

//
